<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function f(arr, x) {
            let resArr = [];
            // 确定原数组是由小到大（1），还是由大到小（2）
            let flag = arr[0] < arr[arr.length - 1] ? 1 : 2;
            if (flag == 1) {
                if (arr[arr.length - 1] <= x) {
                    resArr = resArr.concat(arr, x);
                } else {
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i] >= x) {
                            resArr = resArr.concat(x, arr.slice(i));
                            break;
                        } else {
                            resArr.push(arr[i]);
                        }
                    }
                }
            } else {
                if (arr[arr.length - 1] >= x) {
                    resArr = resArr.concat(arr, x);
                } else {
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i] <= x) {
                            resArr = resArr.concat(x, arr.slice(i));
                            break;
                        } else {
                            resArr.push(arr[i]);
                        }
                    }
                }
            }
            return resArr;
        }

        console.log(f([1, 2, 3, 4, 5], 2));
        console.log(f([1, 2, 3, 4, 5], 0));
        console.log(f([1, 2, 3, 4, 5], 6));
        console.log(f([1, 2, 3, 4, 5], 1.5));

        console.log(f([1, 2, 3, 4, 5].reverse(), 2));
        console.log(f([1, 2, 3, 4, 5].reverse(), 0));
        console.log(f([1, 2, 3, 4, 5].reverse(), 6));
        console.log(f([1, 2, 3, 4, 5].reverse(), 1.5));
    </script>
</body>

</html>